package com.tangding.hprose.api.server.command.impl.control;

import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.tangding.common.exception.GException;
import com.tangding.common.logx.LogHelp;
import com.tangding.common.utils.JacksonUtil;
import com.tangding.hprose.api.client.HproseAsClient;
import com.tangding.hprose.api.server.command.Command;
import com.tangding.hprose.api.server.command.Response;
import com.tangding.hprose.api.server.command.impl.watch.WatchingTable;
import com.tangding.net.pool.BaseNettySessionPool;

/**
 * @description 
 *
 * @author Ranger
 * @version 2017年12月30日_下午9:53:08
 *
 */
@Component
public class InsertControl implements Command{
	
	@Autowired
	BaseNettySessionPool pool;
	
	@Override
	public Response exe(Object... params) throws GException {
		Map<String, Object> user = (Map<String, Object>) params[params.length - 1];
		String uid = (String) user.get("uid");
		String tableId = (String) ((Map<String, Object>) params[0]).get("tableId");
		String gameName = (String) ((Map<String, Object>) params[0]).get("gameName");
		poolExe.submit(new Runnable() {
			public void run() {
				try {
					HproseAsClient.invoke("InsertControl", params[0]);
				} catch (GException e) {
					LogHelp.doLogAppErr(e);
				}
			}
		});
		
		poolExe.submit(new Runnable() {
			public void run() {
				try {
					Map<String, Object> request = new HashMap<>();
					request.put("gameName", gameName);
					request.put("tableId", tableId);
					request.put("showCondition", 7);
					Object result = HproseAsClient.invoke("QueryTableDetails", request);
					if (result != null) {
						Map<String, Object> receivedData = JacksonUtil.readValue(JacksonUtil.toJson(result), Map.class);
						receivedData.put("gameName", gameName);
						receivedData.put("tableId", tableId);
						receivedData.put("showCondition", 1);
						
						pool.doResponse(uid, "UpdateTableDetails", WatchingTable.buildFinalData(1, receivedData));
					}
				} catch (GException e) {
					LogHelp.doLogAppErr(e);
				}
			}
		});
		return doResponseSucc(true);
	}

}
